#!/usr/bin/env python3

'''
Author       : bopo
Date         : 2020-11-19 15:00:48
LastEditors  : bopo
LastEditTime : 2020-12-04 11:28:38
FilePath     : /scripts/ipt5/command.py
Description  :
'''
import sys

from click import option, echo
from click._compat import iteritems

from . import __version__
from .logger import log


def version_option(version=__version__, *param_decls, **attrs):
    if version is None:
        if hasattr(sys, "_getframe"):
            module = sys._getframe(1).f_globals.get("__name__")
        else:
            module = ""

    def decorator(f):
        prog_name = attrs.pop("prog_name", None)
        message = attrs.pop("message", "v%(version)s")

        def callback(ctx, param, value):
            if not value or ctx.resilient_parsing:
                return

            prog = prog_name

            if prog is None:
                prog = ctx.find_root().info_name

            ver = version

            if ver is None:
                try:
                    import pkg_resources
                except ImportError:
                    pass
                else:
                    for dist in pkg_resources.working_set:
                        scripts = dist.get_entry_map().get("console_scripts") or {}
                        for _, entry_point in iteritems(scripts):
                            if entry_point.module_name == module:
                                ver = dist.version
                                break
                if ver is None:
                    raise RuntimeError("Could not determine version")

            echo(message % {"prog": prog, "version": ver}, color=ctx.color)
            ctx.exit()

        attrs.setdefault("help", "Show the version and exit.")
        attrs.setdefault("expose_value", False)
        attrs.setdefault("is_eager", True)
        attrs.setdefault("is_flag", True)
        attrs["callback"] = callback
        return option(*(param_decls or ('-v', "--version",)), **attrs)(f)

    return decorator


def verbose_option(logger=log, *param_decls, **attrs):
    def decorator(f):
        def callback(ctx, param, value):
            if not value or ctx.resilient_parsing:
                return

            if hasattr(logger, "verbose"):
                logger.verbose(value)

        attrs.setdefault("help", "Show detail debug message.")
        attrs.setdefault("expose_value", False)
        attrs.setdefault("is_eager", True)
        attrs.setdefault("is_flag", True)
        attrs["callback"] = callback
        return option(*(param_decls or ('-vv', "--verbose",)), **attrs)(f)

    return decorator
